import type { ProFormInstance } from '@ant-design/pro-form';
import React, { useRef, useState } from 'react';
import { Button, Popconfirm, Tag,  } from 'antd';
import { ActionType, ProColumns, ProTable,DrawerForm } from '@ant-design/pro-components';
import { ArrowRightOutlined, PlusOutlined } from '@ant-design/icons';
import * as api from '@/services/geoip';
import FormIpForm from './FormIpForm';

type FormProps = {
  open: boolean;
  current: API.GeoipIsp | undefined;
  currentParent: API.GeoipIsp | undefined;
  onCancel: () => void;
};

const Form: React.FC<FormProps> = (props) => {
  const { open, onCancel, current, currentParent } = props;
  if (!open) {
    return null;
  }
  
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const [currentIp, setCurrentIp] = useState<API.GeoipIp | undefined>(undefined);
  const [formVisible, setFormVisible] = useState<boolean>(false);
 

  const handleSubmit = async (record: API.GeoipIp) => {
    record.refId = current.id;
    let result: API.Result;
    if (currentIp) {
      result = await api.ipupdate({
        ...currentIp,
        ...record,
      });
    } else {
      result = await api.ipadd({ ...record });
    }

    if (result && result.success === true) {
      setCurrentIp(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };
  
  const handleRemove = async (id: string) => {
    let result = await api.ipremove({key:id});
    if (result && result.success === true) {
      actionRef.current?.reload();
    }
  };
  
  

  
  let columns: ProColumns<API.GeoipIp>[] = [
    {
      title: 'IP',
      dataIndex: 'ip',
      width:160,
      // render: (_, record) => {
      //   return record.subnetMask > 0 ? <>{record.ip}/{record.subnetMask}</> : record.ip;
      // },
    },
    {
      title: '起始IP',
      dataIndex: 'ipStart',
      search:false,
      width:150,
      render: (_, record) => {
        return record.ipStart != record.ipEnd ? <>{record.ipStart}</> : '';
      },
    },
    {
      title: '结束IP',
      dataIndex: 'ipEnd',
      search:false,
      width:150,
      render: (_, record) => {
        return record.ipStart != record.ipEnd ? <>{record.ipEnd}</> : '';
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      search:false,
    },

  ];
  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      render: (_, record) => {
        let cmps = [];

          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrentIp(record);
              }}
            >
              编辑
            </a>,
          );

          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );

        return cmps;
      },
    },
  ]);

  return (
    <DrawerForm<API.GeoipIp>
      open={open}
      width={1000}
      title={`IP管理`}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button
              key="create"
              onClick={() => {
                onCancel();
              }}
            >
              关闭
            </Button>];
        },
      }}
    >

      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        headerTitle={<>ISP运营商：{currentParent ? <><Tag color='blue'>{currentParent?.name}</Tag><ArrowRightOutlined /> </> : ''}<Tag color='blue'>{current.name}</Tag></>}
        columnEmptyText={''}
        formRef={formRef}
        actionRef={actionRef}
        columns={columns}
        search={{
          // span: 8,
          collapsed: false,
          filterType:'light',
        }}
        pagination={false}
        params={{refId: current.id}}
        request={api.iplist}
        toolBarRender={() => {
          var toolbarDoms: any[] = [];

          toolbarDoms.push([
            <Button
              type="primary"
              key="create"
              onClick={() => {
                setFormVisible(true);
                setCurrentIp(undefined);
              }}
            >
              <PlusOutlined />
              新建
            </Button>
          ]);

          return toolbarDoms;
        }}
      />



      
      <FormIpForm
        open={formVisible}
        onSubmit={handleSubmit}
        current={currentIp}
        onCancel={() => {
          setFormVisible(false);
          setCurrentIp(undefined);
        }}
      />

    </DrawerForm>
  );
};

export default Form;
